package com.zkleaner.zookeeper.api;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZooKeeper_Constructor_Usage_Simple implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zookeeper;
    public static void main(String[] args) throws Exception{
        
       zookeeper = new ZooKeeper("127.0.0.1:2181", 
        									5000, //
        									new ZooKeeper_Constructor_Usage_Simple());
        String path = "/zk-leaner";
        System.out.println(zookeeper.getState());
        try {
            connectedSemaphore.await();           
        } catch (InterruptedException e) {}
        System.out.println("ZooKeeper session established.");
        
        zookeeper.create( path, "1243".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL );
        
//      zookeeper.create("/zk-test-ephemeral-", "".getBytes(), 
//	    		Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, 
//	    		new IStringCallback(), "I am context.");
        zookeeper.getData( path, true, new IDataCallback(), null );
        
        zookeeper.setData( path, "123".getBytes(), -1 );   
        
        zookeeper.delete( path, -1 );
    }
    public void process(WatchedEvent event) {
    	System.out.println("Receive watched event：" + event);
        if (KeeperState.SyncConnected == event.getState()) {
  	      if (EventType.None == event.getType() && null == event.getPath()) {
  	          connectedSemaphore.countDown();
  	      } else if (event.getType() == EventType.NodeDataChanged) {
  	          try {
  	        	zookeeper.getData( event.getPath(), true, new IDataCallback(), null );
  	          } catch (Exception e) {}
  	      }
  	    }
       }
}

class IStringCallback implements AsyncCallback.StringCallback{
	  public void processResult(int rc, String path, Object ctx, String name) {
	    System.out.println("Create path result: [" + rc + ", " + path + ", "
	                   + ctx + ", real path name: " + name);
	    }
}

class IDataCallback implements AsyncCallback.DataCallback{
	public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println(rc + ", " + path + ", " + new String(data));
        System.out.println(stat.getCzxid()+","+
                  		   stat.getMzxid()+","+
		                   stat.getVersion());
    }
}
